import { Button } from "antd"
import { useRef, useState, useEffect } from "react"
import PropTypes from "prop-types"

import SchemaForm from "./FormDesigner/SchemaForm"
import CommonModal from "./common/CommonModal"


const ModelerSaveModal = ({
  children,
  modelMetaData,
  beforeShow,
  onSubmit
}) => {

  const formRef = useRef(null)
  const [visible, setVisible] = useState(false)
  const [sending, setSending] = useState(false)

  useEffect(() => {
    if (visible) {
      setTimeout(() => {
        formRef.current.setFieldsValue(modelMetaData)
      })
    }
  }, [visible])

  const handleShow = () => {
    if (beforeShow) {
      beforeShow(() => {
        setVisible(true)
      })
    } else {
      setVisible(true)
    }
  }

  const handleSubmit = () => {
    formRef.current.validateFields().then((values => {
      if (!sending) {
        setSending(true)
        onSubmit(values, {
          clearSending: () => {
            setTimeout(() => {
              setSending(false)
            }, 600);
          },
          hideModal: () => {
            handleCancel()
          }
        })
      }
    }))
  }

  const handleCancel = () => {
    setVisible(false)
  }

  const formItems = [
    {
      name: 'name',
      label: '名称',
      required: true
    },
    {
      name: 'key',
      label: 'key',
      required: true
    },
    {
      type: 'textarea',
      name: 'description',
      label: '说明'
    },
    {
      type: 'boolean',
      name: 'newversion',
      label: '新版本',
      props: {
        tooltip: '将此保存为新版本？这意味着你可以回到以前的版本。'
      }
    },
    {
      type: 'textarea',
      name: 'comment',
      label: '评论',
      hide: (form) => {
        return form.getFieldValue('newversion') === true
      }
    }
  ]

  return <>
    <div onClick={handleShow} style={{ display: 'inline-block' }}>
      {
        children || <Button type="primary">保存</Button>
      }
    </div>
    <CommonModal
      title={`保存模型`}
      visible={visible}
      okButtonProps={{
        loading: sending
      }}
      onCancel={handleCancel}
      onOk={handleSubmit}
    >
      <SchemaForm
        ref={formRef}
        formItems={formItems}
      ></SchemaForm>
    </CommonModal>
  </>
}

ModelerSaveModal.propTypes = {
  modelMetaData: PropTypes.object,
  beforeShow: PropTypes.func,
  onSubmit: PropTypes.func
}

export default ModelerSaveModal